// 认证服务
const API_BASE_URL = 'http://localhost:8080/api/auth'

export interface LoginRequest {
  username: string
  password: string
  rememberMe?: boolean
}

export interface LoginResponse {
  token: string
  refreshToken: string
  userInfo: {
    id: number
    username: string
    email?: string
    roles?: string[]
  }
}

export interface ApiResponse<T> {
  success: boolean
  message: string
  data: T
}

// Token管理
export const TOKEN_KEY = 'accessToken'
export const REFRESH_TOKEN_KEY = 'refreshToken'
export const USER_INFO_KEY = 'userInfo'

// 保存token
export const saveToken = (token: string): void => {
  localStorage.setItem(TOKEN_KEY, token)
}

// 保存刷新token
export const saveRefreshToken = (refreshToken: string): void => {
  localStorage.setItem(REFRESH_TOKEN_KEY, refreshToken)
}

// 保存用户信息
export const saveUserInfo = (userInfo: any): void => {
  localStorage.setItem(USER_INFO_KEY, JSON.stringify(userInfo))
}

// 获取token
export const getToken = (): string | null => {
  return localStorage.getItem(TOKEN_KEY)
}

// 获取刷新token
export const getRefreshToken = (): string | null => {
  return localStorage.getItem(REFRESH_TOKEN_KEY)
}

// 获取用户信息
export const getUserInfo = (): any => {
  const userInfo = localStorage.getItem(USER_INFO_KEY)
  return userInfo ? JSON.parse(userInfo) : null
}

// 清除所有认证信息
export const clearAuth = (): void => {
  localStorage.removeItem(TOKEN_KEY)
  localStorage.removeItem(REFRESH_TOKEN_KEY)
  localStorage.removeItem(USER_INFO_KEY)
}

// 检查是否已登录
export const isAuthenticated = (): boolean => {
  const token = getToken()
  return token !== null && token.length > 0
}

// 登录
export const login = async (loginData: LoginRequest): Promise<ApiResponse<LoginResponse>> => {
  try {
    const response = await fetch(`${API_BASE_URL}/login`, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
      },
      body: JSON.stringify(loginData)
    })

    const result = await response.json()

    if (result.success) {
      // 保存认证信息
      saveToken(result.data.token)
      saveRefreshToken(result.data.refreshToken)
      saveUserInfo(result.data.userInfo)
    }

    return result
  } catch (error) {
    console.error('登录API调用失败:', error)
    throw new Error('网络错误，请检查后端服务是否启动')
  }
}

// 登出
export const logout = async (): Promise<void> => {
  try {
    const token = getToken()
    if (token) {
      // 调用后端登出接口（如果有的话）
      await fetch(`${API_BASE_URL}/logout`, {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
          'Authorization': `Bearer ${token}`
        }
      })
    }
  } catch (error) {
    console.error('登出API调用失败:', error)
  } finally {
    // 清除本地认证信息
    clearAuth()
  }
}

// 刷新token
export const refreshToken = async (): Promise<ApiResponse<{ token: string }>> => {
  try {
    const refreshToken = getRefreshToken()
    if (!refreshToken) {
      throw new Error('没有刷新token')
    }

    const response = await fetch(`${API_BASE_URL}/refresh`, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
      },
      body: JSON.stringify({
        refreshToken: refreshToken
      })
    })

    const result = await response.json()

    if (result.success) {
      saveToken(result.data.token)
    }

    return result
  } catch (error) {
    console.error('刷新token失败:', error)
    clearAuth() // 清除无效的认证信息
    throw error
  }
}

// 检查token是否有效
export const checkTokenValidity = async (): Promise<boolean> => {
  try {
    const token = getToken()
    if (!token) {
      return false
    }

    const response = await fetch(`${API_BASE_URL}/validate`, {
      method: 'GET',
      headers: {
        'Authorization': `Bearer ${token}`
      }
    })

    const result = await response.json()
    return result.success
  } catch (error) {
    console.error('检查token有效性失败:', error)
    return false
  }
} 